package top.atluofu.luofuecommerce.product.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.atluofu.common.exception.BizCode;
import top.atluofu.common.utils.R;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: LuoFuEProductExceptionControllerAdvice
 * @description: 后端数据二次验证
 * @author: 有罗敷的马同学
 * @datetime: 2022Year-10Month-30Day-20:48
 * @Version: 1.0
 */
@Slf4j
@RestControllerAdvice(basePackages = "top/atluofu/luofuecommerce/product/app")
public class LuoFuProductExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("出错了...." + e.getMessage().getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item) -> {
            String defaultMessage = item.getDefaultMessage();
            String field = item.getField();
            map.put(field, defaultMessage);
        });
        return R.error(BizCode.VALID_EXCEPTION.getCode(), BizCode.VALID_EXCEPTION.getMsg()).put("data", map);
    }
}
